﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QAxObject>
#include "windows.h"
#include <QFile>

void MainWindow::excelOper()
{
    // 创建 Excel 对象
    QAxObject excel("Excel.Application");
    if (excel.isNull()) {
        qDebug() << "Error";
        return;
    }
    // 连接异常处理信号
    ExcelHandler handler;
    QObject::connect(&excel, SIGNAL(exception(int, QString, QString, QString)), &handler, SLOT(handleException(int, QString, QString, QString)));
    excel.setProperty("Visible", false);
    // 设置 DisplayAlerts 属性
    excel.setProperty("DisplayAlerts", false);
    // 打开现有 Excel 文件
    QString filePath = "C:\\myself\\2024_waibao\\";
    QString szFileName = "report_template";
    QString excelFile = QString("%1%2.xlsx").arg(filePath).arg(szFileName);
    QAxObject *workbooks = excel.querySubObject("Workbooks");
    QAxObject *workbook = workbooks->querySubObject("Open(const QString&)", excelFile);
    if (workbook->isNull()) {
        qDebug() << "Error1";
        return;
    }
    // 获取第一个工作表
    QAxObject *worksheet = workbook->querySubObject("Worksheets(int)", 1);
    if (worksheet->isNull()) {
        qDebug() << "Error2";
        return;
    }
    // 修改第一个工作表的第一个单元格
    QAxObject *cell = worksheet->querySubObject("Cells(int, int)", 19, 6);
    cell->setProperty("Value", "狗日的");
    cell = worksheet->querySubObject("Cells(int, int)", 19, 7);
    cell->setProperty("Value", "草泥马");
    cell = worksheet->querySubObject("Cells(int, int)", 19, 8);
    cell->setProperty("Value", "赶紧下台，草泥马的");
//    // 保存修改  对于已经打开的文件，不能保存修改
//    workbook->dynamicCall("Save()");
    // 保存 Excel 文件到指定路径（另存为）
    szFileName = "file123_copy";
    QFile::remove(szFileName);
    QString excelFileCopy = QString("%1%2.xlsx").arg(filePath).arg(szFileName);
    workbook->dynamicCall("SaveAs(const QString&)", excelFileCopy);
    // 关闭 Excel 文件
    workbook->dynamicCall("Close()");
    // 关闭 Excel
    excel.dynamicCall("Quit()");
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // 初始化 COM
    CoInitialize(nullptr);


    excelOper();
}

MainWindow::~MainWindow()
{
    // 释放 COM
    CoUninitialize();
    delete ui;
}

